/*
 * Copyright (c)  2015~2020, xforceplus
 * All rights reserved.
 * Project:datacare-orm
 * Id: TemplatePageAnnotationMapperInvokeImpl.java   2020-10-10 11-03-46
 * Author: Evan
 */
package cn.datacare.orm.mapper.impl;

import cn.datacare.orm.manager.impl.SQLManager;
import cn.datacare.orm.mapper.MapperInvoke;
import cn.datacare.orm.query.PageQuery;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * Title:
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Copyright: 2015~2020
 * </p>
 * <p>
 * Company/Department: xforceplus
 * </p>
 *
 * @author Evan
 * <b>Creation Time:</b> 2020-10-10 11-03-46
 * @since V1.0
 */
public class TemplatePageAnnotationMapperInvokeImpl implements MapperInvoke {

    /***
     * Mapper 调用
     * @param sqlManager
     * @param entityClass
     * @param sqlId
     * @param method
     * @param args
     * @return Object
     */
    @Override
    public Object call(SQLManager sqlManager, Class entityClass, String sqlId, Method method, Object[] args) {
        PageQuery query = (PageQuery) args[0];
        Object obj = query.getParas();
        long totalRow = 0;
        if (query.getTotalRow() < 0) {
            totalRow = sqlManager.templateCount(entityClass, obj);
            query.setTotalRow(totalRow);
        }
        List<Object> list = null;
        if (totalRow == 0) {
            list = new ArrayList(0);
        } else {
            long start = (sqlManager.isOffsetStartZero() ? 0 : 1) + (query.getPageNumber() - 1) * query.getPageSize();
            long size = query.getPageSize();
            if (query.getOrderBy() != null && query.getOrderBy().trim().length() != 0) {
                list = sqlManager.template(entityClass, obj, start, size, query.getOrderBy());
            } else {
                list = sqlManager.template(entityClass, obj, start, size);
            }
        }
        query.setList(list);
        return query;
    }
}
